package com.rabbitmq.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

/**
 * @Author： yu.Tan
 * @Date: 2020/8/20 17:09
 * @Description:
 */
@Configuration
public class RabbitMQConfig {


    //没有被正确路由的消息  备份队列
    private static final String MESSAGE_BAK_QUEUE_NAME = "un_routing_queue_name";
    //没有被正确路由的消息  备份交换机
    private static final String MESSAGE_BAK_EXCHANGE_NAME = "un_routing_exchange_name";

    //死信队列
    private static final String DEAD_LETTERS_QUEUE_NAME = "dead_letters_queue_name";
    //死信交换机
    private static final String DEAD_LETTERS_EXCHANGE_NAME = "dead_letters_exchange_name";

    //目标队列
    private static final String QUEUE_NAME = "test_dlx_queue_name";
    //目标消息交换机
    private static final String EXCHANGE_NAME = "test_dlx_exchange_name";
    //ROUTING_KEY
    private static final String ROUTING_KEY = "user.add";

    /**
     * 声明备份队列、备份交换机、绑定队列到备份交换机
     * 建议使用FanoutExchange广播式交换机
     */
    @Bean
    public Queue msgBakQueue() {
        return new Queue(MESSAGE_BAK_QUEUE_NAME);
    }

    @Bean
    public FanoutExchange msgBakExchange() {
        return new FanoutExchange(MESSAGE_BAK_EXCHANGE_NAME);
    }

    @Bean
    public Binding msgBakBinding() {
        return BindingBuilder.bind(msgBakQueue()).to(msgBakExchange());
    }

    /**
     * 声明死信队列、死信交换机、绑定队列到死信交换机
     * 建议使用FanoutExchange广播式交换机
     */
    @Bean
    public Queue deadLettersQueue() {
        return new Queue(DEAD_LETTERS_QUEUE_NAME);
    }

    @Bean
    public FanoutExchange deadLettersExchange() {
        return new FanoutExchange(DEAD_LETTERS_EXCHANGE_NAME);
    }

    @Bean
    public Binding deadLettersBinding() {
        return BindingBuilder.bind(deadLettersQueue()).to(deadLettersExchange());
    }

    /**
     * 声明普通队列，并指定相应的备份交换机、死信交换机
     */
    @Bean
    public Queue queue(){
        Map<String,Object> arguments=new HashMap<>(10);
        //指定死信发送的Exchange
        arguments.put("x-dead-letter-exchange", DEAD_LETTERS_EXCHANGE_NAME);
        return new Queue(QUEUE_NAME, true, false, false, arguments);
    }


    @Bean
    public Exchange exchange() {
        Map<String, Object> arguments = new HashMap<>(10);
        //声明备份交换机
        arguments.put("alternate-exchange", MESSAGE_BAK_EXCHANGE_NAME);
        return new DirectExchange(EXCHANGE_NAME, true, false, arguments);
    }

    @Bean
    public Binding binding() {
        return BindingBuilder.bind(queue()).to(exchange()).with(ROUTING_KEY).noargs();
    }

}
